import React, { useContext } from 'react';
import { BrowserRouter, Route, Switch, RouteProps, Redirect } from 'react-router-dom';
import './App.css';
import Login from './pages/login/Login';
import Home from './pages/Home/Home';
import LayoutMaster from './layouts/LayoutMaster';
import About from './pages/Home/About';
import authContext from './stores/auth.store';
import { observer } from 'mobx-react';

const PrivateRoute: React.FC<RouteProps> = observer(({ children, ...rest }) => {
	const auth = useContext(authContext);

	return (
		<Route
			{...rest}
			render={({ location }) =>
				auth.isLogined ? (
					<LayoutMaster>{children}</LayoutMaster>
				) : (
					<Redirect
						to={{
							pathname: '/login',							
							state: { from: location }
						}}
					/>
				)}
		/>
	);
});

const App: React.FC = () => {
	return (
		<BrowserRouter>
			<Switch>
				<PrivateRoute exact path="/">
					<Home />
				</PrivateRoute>
				<PrivateRoute path="/about">
					<About />
				</PrivateRoute>
				<Route path="/login">
					<Login />
				</Route>
			</Switch>
		</BrowserRouter>
	);
};

export default App;
